package backtracking;

public class PathWithMaximumGold1219 {
    int max = 0;
    public int getMaximumGold(int[][] grid) {
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if(grid[i][j]==0){
                    continue;
                }
                backtracing(i,j,grid,0);
            }
        }
        return max;
    }

    private void backtracing(int i, int j, int[][] grid, int sum) {
        if(i<0||i>=grid.length||j<0||j>=grid[0].length||grid[i][j]==0){
            max = Math.max(sum,max);
            return;
        }
        sum+=grid[i][j];
        int temp = grid[i][j];
        grid[i][j] = 0;
        backtracing(i+1,j,grid,sum);
        backtracing(i-1,j,grid,sum);
        backtracing(i,j+1,grid,sum);
        backtracing(i,j-1,grid,sum);
        grid[i][j] = temp;
    }
}
